#-*-coding:utf8-*-
import simplejson
from dateutil import parser

from basic import MongoDBCollectionHandler
from orm import TweetAccount


class AccountCollection(MongoDBCollectionHandler):
    '''
    Class that handles tw_account collection
    It stores account information of users
    '''
    collection_name = "tw_account"

    def __init__(self):
        super(AccountCollection, self).\
                __init__(AccountCollection.collection_name)
        if (self.col_handler.count() == 0):
            print "Row count is 0. It might be the first time to use " + \
                    AccountCollection.collection_name + " collection."
            self.col_handler.ensure_index(\
                    [("user_id", 1), ("screen_name", 1)], unique=True)

    def insert_or_update(self, user_info_json):
        '''
        Insert user_info into the collection. Update when there is already
        user which have same screen_name.
        @rtype TweetAccount (which is inserted or updated)
        @param user_info_json : string
        '''

        user_info = simplejson.loads(user_info_json)

        screen_name = user_info["screen_name"]
        user_id = long(user_info["id"])
        created_at = parser.parse(user_info["created_at"])
        bio = user_info["description"]
        profile_img_url = user_info["profile_image_url"]

        document = {"screen_name": screen_name,
                    "user_id": user_id,
                    "created_at": created_at,
                    "bio": bio,
                    "profile_image_url": profile_img_url}

        check = self.col_handler.find_one({"screen_name": screen_name})
        if(check != None):
            self.col_handler.update({"screen_name": screen_name}, \
                    {"$set": document})
        else:
            self.col_handler.insert(document)

        return TweetAccount(self.col_handler.\
                find_one({"screen_name": screen_name}))

    def query_by_id(self, user_id):
        '''
        Return TweetAccount of the account which id is 'user_id'
        @rtype TweetAccount
        @param user_id : long
        '''

        user = self.col_handler.find_one({"user_id": user_id})
        return TweetAccount(user)

    def query_by_screen_name(self, screen_name):
        '''
        Return TweetAccount of the account which screen_name is 'screen_name'
        @rtype TweetAccount
        @param screen_name : string
        '''

        user = self.col_handler.find_one({"screen_name": screen_name})
        return TweetAccount(user)

if __name__ == "__main__":
    account_coll = AccountCollection()
    aa = open("test", "r")
    test = aa.readline()
    aa.close()
    print unicode(account_coll.insert_or_update(test))
    print unicode(account_coll.query_by_screen_name("twitterapi"))
    print unicode(account_coll.query_by_id(6253282L))
